#pragma once

#include <iostream>
#include <string>
#include <string.h>
#include <strings.h>    // bzero
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <unordered_map>

#include "Log.hpp"
Log lg;

uint16_t defaultport = 8888;
std::string defaultip = "0.0.0.0";
using func_t = std::function<std::string(const std::string&)>;

enum{
    SOCKET_ERR = 1,
    BIND_ERR
};

class UdpServer
{
public:
    UdpServer(uint16_t &port = defaultport, const std::string &ip = defaultip)
        :sockfd_(0), port_(port), ip_(ip), isrunning(false)
    {}
    ~UdpServer()
    {
        if(sockfd_ > 0)
            close(sockfd_);
    }
public:
    void Init()
    {
        // 1.创建udp socket套接字
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if(sockfd_ < 0)
        {
            lg(Fatal, "socket create error, errno: %d, error message: %s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        lg(Info, "socket create success, sockfd: %d", sockfd_);

        // 2.绑定端口号
        struct sockaddr_in local;
        bzero(&local, sizeof(local));   // 将local内部清零
        // 填充 socket套接字相关字段
        local.sin_family = AF_INET;     // 当前结构体的地址类型
        local.sin_port = htons(port_);  // 当前服务器的端口号，须将主机序列转换成网络序列
        local.sin_addr.s_addr = inet_addr(ip_.c_str());     // 网络中的ip序列是4字节传输的，所以将字符串风格的ip地址转换成可以在网络中传输的4字节Ip网络序列
        // 开始绑定，bind本质就是将上面一系列参数设置进内核，到指定的套接字中
        int n = bind(sockfd_, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            lg(Fatal, "bind error, error: %d, err message: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "bind success, errno: %d, err message: %s", errno, strerror(errno));
    }

    void CheckUser(const struct sockaddr_in& client, const std::string clientip, const uint16_t clientport)
    {
        auto iter = online_user_.find(clientip);
        if(iter == online_user_.end())
        {
            // 找不到
            online_user_.insert({clientip, client});
            std::cout << "[" << clientip << ":" << clientport << "] add to online_user..." << std::endl;
        }
    }

    void Broadcast(const std::string& info, const std::string clientip, const uint16_t clientport)
    {
        for(const auto& user : online_user_)
        {
            std::string message = "[" + clientip + ":" + std::to_string(clientport) + "]#";
            message += info;
            socklen_t len = sizeof(user.second);
            sendto(sockfd_, message.c_str(), message.size(), 0, (const sockaddr*)(&user.second), len);
        }
    }

    // 让服务器执行特定的函数功能
    // void Run(func_t func)   
    void Run()   
    {
        isrunning = true;
        char inbuffer[SIZE];
        while (isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(sockfd_, inbuffer, sizeof(inbuffer), 0, (struct sockaddr*)&client, &len);
            if(n < 0)
            {
                lg(Warning, "recvfrom error, errno: %d, err message: %s", errno, strerror(errno));
                continue;
            }

            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);
            CheckUser(client, clientip, clientport);    // 判断用户是否在群聊中

            std::string info = inbuffer;
            Broadcast(info, clientip, clientport);      // 给每一个群聊中的用户都发送消息


            // // 此时服务端的数据，我们已经拿到了并将其存至了 inbuffer里面
            // inbuffer[n] = 0;    //在结尾添加'\0'
            // std::string info = inbuffer;   
            // // std::string echo_string = "server say@ " + info;
            // std::string echo_string = func(info);

            // // 向客户端发送信息
            // ssize_t r = sendto(sockfd_, echo_string.c_str(), echo_string.size(), 0, (const sockaddr*)&client, len);
            // if(r < 0)
            // {
            //     lg(Warning, "sendto error, errno: %d, err message: %s", errno, strerror(errno));
            //     continue;
            // }
        }
    }
private:
    int sockfd_;    // 网络文件描述符
    std::string ip_;    // IP
    uint16_t port_;     // 表明服务器进程的端口号
    bool isrunning;     // 服务器是否运行

    std::unordered_map<std::string, struct sockaddr_in> online_user_;
};